package com.jwdf.uda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.event.ThirdPartEvent;
import com.jwdf.uda.event.UserEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.QqLoginAction;
import com.jwdf.uda.http.action.UpdateDeviceInfo;
import com.jwdf.uda.http.action.WechatLoginAction;
import com.jwdf.uda.http.action.WeiboLoginAction;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.ui.fragment.user.bean.UserSession;
import com.jwdf.uda.ui.fragment.user.login.LoginEntryFragment;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;

import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/5/25.
 */
public class LoginActivity extends AbsTitleBarActivity {

    public static void start(Context context) {
        context.startActivity(new Intent(context, LoginActivity.class));
    }

    public static void start(Context context, String mobile) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra("mobile", mobile);
        context.startActivity(intent);
    }

    @Override
    protected String getTopTitle() {
        return getString(R.string.login);
    }

    @Override
    protected BaseFragment onCreateContentFragment() {
        return new LoginEntryFragment();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
    }
    @Override
    protected void setupTitleView() {
        setOperateTitle(getString(R.string.register));
    }
    @Override
    protected Bundle onPutArguments() {
        Bundle args = new Bundle();
        args.putString("mobile", getIntent().hasExtra("mobile") ? getIntent().getStringExtra("mobile") : "");
        return args;
    }
    @Override
    public void onHeadActionClick(View view) {
        startNewActivity(RegisterActivity.class);
    }
    @Override
    protected void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        super.onDestroy();
    }
    public void onEvent(UserEvent event) {
        switch (event.getEvent()) {
            case UserEvent.EVENT_LOGIN:
//                if (ConfigUtils.isStylist(LoginActivity.this)) {
//                    startNewActivity(StylistActivity.class);
//                } else {
                    startNewActivity(DefaultMainActivity.class);
//                }
                finish();
                break;
            case UserEvent.EVENT_STEP_4:
                finish();
            case UserEvent.EVENT_GO_LOGIN:
                finish();
                break;
        }
    }
    public void onEvent(ThirdPartEvent event) {
        if (ThirdPartEvent.EVENT_AUTH_COMPLETE == event.getEvent()) {
            if (Wechat.NAME.equals(event.loginType)) {
                wechatLogin(event.usrOpenId, event.usrName, event.usrPic);
            } else if(QQ.NAME.equals(event.loginType)){
               qqLogin(event.usrOpenId, event.usrName, event.usrPic);
            }else {
                weiboLogin(event.usrOpenId, event.usrName, event.usrPic);
            }
        } else if (ThirdPartEvent.EVENT_COMPLETE_INFO == event.getEvent()) {
//            if (ConfigUtils.isStylist(LoginActivity.this)) {
//                startNewActivity(StylistActivity.class);
//            } else {
                startNewActivity(DefaultMainActivity.class);
//            }
            finish();
        }
    }
    private void wechatLogin(String openId, final String nick, final String avatar) {
        onNewRequestCall(WechatLoginAction.newInstance(this, openId).request(new AHttpService.IResCallback<PbBean.PbResUserWechatLogin>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserWechatLogin> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (HttpHelper.showError(LoginActivity.this, resultCode, baseServerInfo, getString(R.string.error_net))) {
                    EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                    return;
                }
                PbBean.PbResUserWechatLogin userLogin = response.body();
                if (userLogin != null) {
                    if (userLogin.getUserInfo().getIsNewVisitor()) {
                        EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                        ConfigUtils.setCurrentUser(LoginActivity.this, new UserSession(userLogin.getSessionId(), userLogin.getToken()));
                        VisitorUpdateInfoActivity.start(LoginActivity.this, nick, avatar, false);
                    } else {
                        UserSession userSession = new UserSession(userLogin.getSessionId(), userLogin.getToken());
                        userSession.setUserId(userLogin.getUserInfo().getUserId());
                        userSession.setStylist(userLogin.getUserInfo().getIsDesigner());
                        userSession.setUCoin(userLogin.getUserInfo().getMoney());
                        userSession.setUserName(userLogin.getUserInfo().getUsername());
                        ConfigUtils.setCurrentUser(LoginActivity.this, userSession);
                        if (!ConfigUtils.isRejectPrivacyPermission(LoginActivity.this)) {
                            reportDeviceInfo(LoginActivity.this);
                        } else {
                            EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                            UserEvent event = new UserEvent();
                            event.setEvent(UserEvent.EVENT_LOGIN);
                            EventBusUtil.post(event);
                        }
                    }
                }
            }
        }));
    }
    private void reportDeviceInfo(final Context context) {
        PushAgent.getInstance(context).enable(new IUmengRegisterCallback() {
            @Override
            public void onRegistered(final String deviceToken) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        onNewRequestCall(UpdateDeviceInfo.newInstance(context, deviceToken).request(new AHttpService.IResCallback<PbBean.PbResSystemUpdateDeviceInfo>() {
                            @Override
                            public void onCallback(int resultCode, Response<PbBean.PbResSystemUpdateDeviceInfo> response, PbBean.PbBaseServerInfo
                                                                                                                                                            baseServerInfo) {
                                EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                                if(response != null) {
                                    if(HttpHelper.showError(context, resultCode, baseServerInfo, getString(R.string.error_net))) {
                                    }
                                    PbBean.PbResSystemUpdateDeviceInfo deviceInfo = response.body();
                                    if(deviceInfo != null) {
                                        ConfigUtils.setPageLength(context, deviceInfo.getPageLength());
                                        ConfigUtils.setAboutPage(context, deviceInfo.getAboutPage());
                                        ConfigUtils.setUserProtocol(context, deviceInfo.getUserProtocolPage());
                                    }
                                }
                                UserEvent event = new UserEvent();
                                event.setEvent(UserEvent.EVENT_LOGIN);
                                EventBusUtil.post(event);
                            }
                        }));
                    }
                });
            }
        });
    }
    private void weiboLogin(String openId, final String nick, final String avatar) {
        onNewRequestCall(WeiboLoginAction.newInstance(this, openId).request(new AHttpService.IResCallback<PbBean.PbResUserWeiboLogin>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserWeiboLogin> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (HttpHelper.showError(LoginActivity.this, resultCode, baseServerInfo, getString(R.string.error_net))) {
                    EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                    return;
                }
                PbBean.PbResUserWeiboLogin userLogin = response.body();
                if (userLogin != null) {
                    if (userLogin.getUserInfo().getIsNewVisitor()) {
                        EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                        ConfigUtils.setCurrentUser(LoginActivity.this, new UserSession(userLogin.getSessionId(), userLogin.getToken()));
                        VisitorUpdateInfoActivity.start(LoginActivity.this, nick, avatar, false);
                    } else {
                        UserSession userSession = new UserSession(userLogin.getSessionId(), userLogin.getToken());
                        userSession.setUserId(userLogin.getUserInfo().getUserId());
                        userSession.setStylist(userLogin.getUserInfo().getIsDesigner());
                        userSession.setUCoin(userLogin.getUserInfo().getMoney());
                        userSession.setUserName(userLogin.getUserInfo().getUsername());
                        ConfigUtils.setCurrentUser(LoginActivity.this, userSession);
                        if (!ConfigUtils.isRejectPrivacyPermission(LoginActivity.this)) {
                            reportDeviceInfo(LoginActivity.this);
                        } else {
                            EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                            UserEvent event = new UserEvent();
                            event.setEvent(UserEvent.EVENT_LOGIN);
                            EventBusUtil.post(event);
                        }
                    }
                }
            }
        }));
    }

    private void qqLogin(String openId, final String nick, final String avatar) {
        onNewRequestCall(QqLoginAction.newInstance(this, openId).request(new AHttpService.IResCallback<PbBean.PbResUserQqLogin>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserQqLogin> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (HttpHelper.showError(LoginActivity.this, resultCode, baseServerInfo, getString(R.string.error_net))) {
                    EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                    return;
                }
                PbBean.PbResUserQqLogin userLogin = response.body();
                if (userLogin != null) {
                    if (userLogin.getUserInfo().getIsNewVisitor()) {
                        EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                        ConfigUtils.setCurrentUser(LoginActivity.this, new UserSession(userLogin.getSessionId(), userLogin.getToken()));
                        VisitorUpdateInfoActivity.start(LoginActivity.this, nick, avatar, false);
                    } else {
                        UserSession userSession = new UserSession(userLogin.getSessionId(), userLogin.getToken());
                        userSession.setUserId(userLogin.getUserInfo().getUserId());
                        userSession.setStylist(userLogin.getUserInfo().getIsDesigner());
                        userSession.setUCoin(userLogin.getUserInfo().getMoney());
                        userSession.setUserName(userLogin.getUserInfo().getUsername());
                        ConfigUtils.setCurrentUser(LoginActivity.this, userSession);
                        if (!ConfigUtils.isRejectPrivacyPermission(LoginActivity.this)) {
                            reportDeviceInfo(LoginActivity.this);
                        } else {
                            EventBusUtil.post(new ThirdPartEvent(ThirdPartEvent.EVENT_CLOSE_PROGRESS));
                            UserEvent event = new UserEvent();
                            event.setEvent(UserEvent.EVENT_LOGIN);
                            EventBusUtil.post(event);
                        }
                    }
                }
            }
        }));
    }



}
